﻿using FastORM.Applicaiton;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FastExecutor.ORG.Util
{
    public class DataBuilder
    {
        public static DBUtil dbutil = new DBUtil();
        public static string CreateTableFieldCodeValue(string TableName, string KeyFieldName, string CodeFieldName, string ParentGuidName, string ParentGuid)
        {
            string Code = string.Empty;
            if (ParentGuid == "Top")
            {
                string SQL = string.Format("select max({0}) from {1} where {2}='Top'", CodeFieldName, TableName, ParentGuidName);
                string RecordCode = Convert.ToString(dbutil.ExecuteScar(SQL));
                if (string.IsNullOrEmpty(RecordCode))
                {
                    Code = "1000";
                }
                else
                {
                    Code = (Convert.ToInt64(RecordCode) + 1).ToString();
                }
            }
            else
            {
                DBRow record = new DBRow(TableName, KeyFieldName, ParentGuid);
                string ParentCode = Convert.ToString(record[CodeFieldName]);
                string SQL = string.Format("select max({0}) from {1} where LENGTH({0})={2} and {0} like '{3}%'", CodeFieldName, TableName, ParentCode.Length + 4, ParentCode);
                string RecordCode = Convert.ToString(dbutil.ExecuteScar(SQL));
                if (string.IsNullOrEmpty(RecordCode))
                {
                    Code = ParentCode + "1000";
                }
                else
                {
                    Code = (Convert.ToInt64(RecordCode) + 1).ToString();
                }

            }
            return Code;
        }
    }
}
